package com.egene.tw.blue;

import android.content.Context;
import android.os.Handler;

import com.egene.tw.bus.BusHelper;
import com.egene.tw.bus.DropDownEvent;
import com.egene.tw.bus.LoadDataEndEvent;
import com.egene.tw.bus.MeasureEndEvent;
import com.egene.tw.data.DataRepository;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.UploadJobService;
import com.egene.tw.data.entity.DeviceSetting;
import com.egene.tw.data.utils.CalUtils;
import com.egene.tw.data.utils.DateFormUtils;
import com.egene.tw.data.entity.BloodData;
import com.egene.tw.data.entity.FatigueData;
import com.egene.tw.data.entity.HeartData;
import com.egene.tw.data.entity.OxygenData;
import com.egene.tw.data.entity.SleepData;
import com.egene.tw.data.entity.StepData;
import com.egene.tw.data.wrapper.OneKeyMeasureData;
import com.weike.chiginon.DataPacket;
import com.weike.manager.CommandManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * Created by wzx on 2018/6/25.
 */

public class DataParser {
    private static DataParser INSTANCE;

    public static DataParser generate(CommandManager manager, Context context) {
        if (INSTANCE == null) {
            INSTANCE = new DataParser(manager, context.getApplicationContext());
        }
        return INSTANCE;
    }

    public enum Cmd {
        drop_down, one_key_measure, sleep, heart_once, heart_rt, oxygen_once, oxygen_rt, blood_once, blood_rt
    }

    public enum Status {
        idle, receiving
    }

    private CommandManager manager;
    private Status status = Status.idle;
    private Cmd cmd;
    private long lastReceiveDataTime;
    private Disposable timeChecker;
    private Handler handler = new Handler();
    private float egeneValue;
    private Context context;

    private List<ArrayList<Byte>> dataList = new ArrayList<>();


    private DataParser(CommandManager manager, Context context) {
        this.manager = manager;
        this.context = context;

        DeviceSetting deviceSetting = RealmHelper.loadSettings();
        egeneValue = deviceSetting.getEgeneValue();
    }

    public void receive(DataPacket dataPacket) {
        lastReceiveDataTime = System.currentTimeMillis();
        if (cmd == Cmd.drop_down) {
            //整点数据第二个包
            if (dataPacket.commandID == 0) {
                if (dataList.size() > 0) {
                    dataList.get(dataList.size() - 1).addAll(dataPacket.data);
                }
            } else {
                dataList.add(dataPacket.data);
            }
//            dealDropDown(dataPacket);
        } else if (cmd == Cmd.one_key_measure) {
            dealOneKeyMeasure(dataPacket);
        } else if (cmd == Cmd.heart_once
                || cmd == Cmd.heart_rt
                || cmd == Cmd.oxygen_once
                || cmd == Cmd.oxygen_rt
                || cmd == Cmd.blood_once
                || cmd == Cmd.blood_rt) {
            dealMeasure(dataPacket);
        } else if (cmd == Cmd.sleep) {
            dealSleep(dataPacket);
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    public void getBattery() {
        manager.getBattery();
    }

    public void shake() {
        manager.findBand();
    }

    public void dropDown() {
        dataList.clear();
        cmd = Cmd.drop_down;
        status = Status.receiving;


        BluetoothLeServiceV2.isDropDownRefresh = true;
        BusHelper.post(new DropDownEvent(true));

        manager.setSyncData(System.currentTimeMillis() - 7 * 24 * 3600 * 1000);//发这个时间点之后 的数据过来  ， 7天前的数据不发过来

        startTimeChecker();
    }

    public void sleep() {
        cmd = Cmd.sleep;
        status = Status.receiving;
        manager.setSyncSleepData(System.currentTimeMillis() - 7 * 24 * 3600 * 1000);
        startTimeChecker();
    }

    ///////////////////////////////////////////////////////////////////////////
    // 一键测量
    ///////////////////////////////////////////////////////////////////////////
    public void oneKeyMeasureStart() {
        cmd = Cmd.one_key_measure;
        status = Status.receiving;
        manager.oneKeyMeasure(1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                50000);
    }

    public void oneKeyMeasureEnd() {
        manager.oneKeyMeasure(0);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 心率
    ///////////////////////////////////////////////////////////////////////////
    public void heartOnceStart() {
        cmd = Cmd.heart_once;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X09, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                30000);
    }

    public void heartOnceEnd() {
        manager.realTimeAndOnceMeasure(0X09, 0);
    }

    public void heartRTStart() {
        cmd = Cmd.heart_rt;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X0A, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                30000);
    }

    public void heartRTEnd() {
        manager.realTimeAndOnceMeasure(0X0A, 0);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 血压
    ///////////////////////////////////////////////////////////////////////////
    public void bloodOnceStart() {
        cmd = Cmd.blood_once;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X21, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                50000);
    }

    public void bloodOnceEnd() {
        manager.realTimeAndOnceMeasure(0X21, 0);
    }

    public void bloodRTStart() {
        cmd = Cmd.blood_rt;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X22, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                50000);
    }

    public void bloodRTEnd() {
        manager.realTimeAndOnceMeasure(0X22, 0);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 血氧
    ///////////////////////////////////////////////////////////////////////////

    public void oxygenOnceStart() {
        cmd = Cmd.oxygen_once;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X11, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                50000);
    }

    public void oxygenOnceEnd() {
        manager.realTimeAndOnceMeasure(0X11, 0);
    }

    public void oxygenRTStart() {
        cmd = Cmd.oxygen_rt;
        status = Status.receiving;
        manager.realTimeAndOnceMeasure(0X12, 1);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        stopTransport();
                    }
                },
                50000);
    }

    public void oxygenRTEnd() {
        manager.realTimeAndOnceMeasure(0X12, 0);
    }


    public void stopTransport() {
        stopTimeChecker();
        if (cmd == null) {
            return;
        }
        if (status != Status.receiving) {
            return;
        }
        status = Status.idle;
        switch (cmd) {
            case drop_down:
                dealDropDown();
                break;
            case one_key_measure:
                oneKeyMeasureEnd();
                break;
            case sleep:
                //
                break;
            case heart_once:
                heartOnceEnd();
                break;
            case heart_rt:
                heartRTEnd();
                break;
            case oxygen_once:
                oxygenOnceEnd();
                break;
            case oxygen_rt:
                oxygenRTEnd();
                break;
            case blood_once:
                bloodOnceEnd();
                break;
            case blood_rt:
                bloodRTEnd();
                break;
        }
        BusHelper.post(new MeasureEndEvent());
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////

    private void dealDropDown() {
        long currTime = System.currentTimeMillis();
        String currUserId = DataRepository.getInstance().currUserId();

        Map<Long, StepData> stepMap = new TreeMap<>();
        Map<Long, SleepData> sleepMap = new TreeMap<>();


        List<StepData> stepDataList = new ArrayList<>();
        List<SleepData> sleepDataList = new ArrayList<>();
        List<HeartData> heartDataList = new ArrayList<>();
        List<OxygenData> oxygenDataList = new ArrayList<>();
        List<BloodData> bloodDataList = new ArrayList<>();
        List<FatigueData> fatigueDataList = new ArrayList<>();

        for (ArrayList<Byte> datas : dataList) {
            log(byteArrayToString(datas));
            //byte ---> int
            ArrayList<Integer> data = new ArrayList<>();
            for (int i = 0; i < datas.size(); i++) {
                int ii = datas.get(i) & 0xff;
                data.add(ii);
            }
            //整点数据第一个包
            if (data.get(0) == 0X51 && data.get(1) == 0x20 && data.size() >= 21) {
                //整点测量存储值(计步、卡路里、心率、血氧、血压、睡眠时间)
                //接收的数据：51 20 12 06 18 0B 00 02 C5 00 00 09 00 00 00 00
                //接收的数据：01 36 01 0B 01
                //12 06 18 0B：年月日时
                //00 02 C5：计步
                //00 00 09：kcal
                //00 00 00 00：心率、血氧、收缩压、舒张压
                //01 36：浅度睡眠小时值、分钟值
                //01 0B：深度睡眠小时值、分钟值
                //01 ：醒来次数
                int year = data.get(2);
                int month = data.get(3);
                int day = data.get(4);
                int hour = data.get(5);

                int step = byteArrayToInt(new byte[]{0, datas.get(6), datas.get(7), datas.get(8)});
                int kcal = byteArrayToInt(new byte[]{0, datas.get(9), datas.get(10), datas.get(11)});
                int heart = data.get(12);
                int oxygen = data.get(13);
                int bloodHigh = data.get(14);
                int bloodLow = data.get(15);

                int qsHour = data.get(16);
                int qsMin = data.get(17);
                int ssHour = data.get(18);
                int ssMin = data.get(19);
                int walkingTimes = data.get(20);

                log(year + "年" + month + "月" + day + "日  " + hour + "时");
                log("步数：" + step);
                log("kcal：" + kcal);
                log("心率：" + heart);
                log("血氧：" + oxygen);
                log("血压：" + bloodHigh + "  " + bloodLow);

                log("浅睡：" + qsHour + ":" + qsMin);
                log("深睡：" + ssHour + ":" + ssMin);
                log("醒来次数：" + walkingTimes);

                long time = DateFormUtils.parse2Long(year, month, day, 0, 0);
                long time2 = DateFormUtils.parse2Long(year, month, day, hour, 0);


                //step
                StepData stepData = stepMap.get(time);
                if (stepData == null
                        || stepData.getValue() < step) {
                    stepData = new StepData();
                    stepData.setTime(time);
                    stepData.setValue(step);
                    stepData.setKcal(kcal);
                    stepData.setDetailTime(currTime);
                    stepData.setUserId(currUserId);

                    stepMap.put(time, stepData);
                } else {
                    stepData.setDetailTime(currTime);
                }

                //sleep
                SleepData sleepData = sleepMap.get(time);
                if (sleepData == null
                        || ssMin != 0 || ssHour != 0
                        || qsHour != 0 || qsMin != 0
                        || walkingTimes != 0) {
                    sleepData = new SleepData();
                    sleepData.setTime(time);
                    sleepData.setDeepValue(ssMin + ssHour * 60);
                    sleepData.setShallowValue(qsMin + qsHour * 60);
                    sleepData.setWalkingTimes(walkingTimes);
                    sleepData.setDetailTime(currTime);
                    sleepData.setUserId(currUserId);

                    sleepMap.put(time, sleepData);
                }else {
                    sleepData.setDetailTime(currTime);
                }

                //fatigue
                FatigueData fatigueData = new FatigueData();
                fatigueData.setTime(time2);

                fatigueData.setStep(step);
                fatigueData.setKcal(kcal);
                fatigueData.setDeepValue(ssMin + ssHour * 60);
                fatigueData.setShallowValue(qsMin + qsHour * 60);
                fatigueData.setHeart(heart);
                fatigueData.setOxygen(oxygen);
                fatigueData.setBloodHigh(bloodHigh);
                fatigueData.setBloodLow(bloodLow);

                float point = CalUtils.calFatigue(fatigueData, egeneValue);
                fatigueData.setValue(point);

                fatigueData.setUserId(currUserId);
                fatigueDataList.add(fatigueData);

                //heart
                if (heart != 0) {
                    HeartData heartData = new HeartData();
                    heartData.setTime(time2);
                    heartData.setValue(heart);
                    heartData.setUserId(currUserId);
                    heartDataList.add(heartData);
                }
                //oxygen
                if (oxygen != 0) {
                    OxygenData oxygenData = new OxygenData();
                    oxygenData.setTime(time2);
                    oxygenData.setValue(oxygen);
                    oxygenData.setUserId(currUserId);
                    oxygenDataList.add(oxygenData);
                }
                //blood
                if (bloodHigh != 0 || bloodLow != 0) {
                    BloodData bloodData = new BloodData();
                    bloodData.setTime(time2);
                    bloodData.setHighValue(bloodHigh);
                    bloodData.setLowValue(bloodLow);
                    bloodData.setUserId(currUserId);
                    bloodDataList.add(bloodData);
                }
            }

            //下拉数据
            if (data.get(0) == 0x51) {
                if (data.get(1) == 0x08) {
                    //当前计步、卡路里、睡眠值
                    //51 08 00 18 44 00 00 54 00 00 00 00 00
                    //00 18 44:步数
                    //00 00 54 :kcal
                    //00 00 00 00 00 :浅度睡眠小时值、浅度睡眠分钟值、深度睡眠小时值、深度睡眠分钟值、醒来次数
                    int step = byteArrayToInt(new byte[]{0, datas.get(2), datas.get(3), datas.get(4)});
                    int kcal = byteArrayToInt(new byte[]{0, datas.get(5), datas.get(6), datas.get(7)});
                    int qsHour = data.get(8);
                    int qsMin = data.get(9);
                    int ssHour = data.get(10);
                    int ssMin = data.get(11);
                    int walkingTimes = data.get(12);


                    log("步数：" + step);
                    log("kcal：" + kcal);
                    log("浅睡：" + qsHour + ":" + qsMin);
                    log("深睡：" + ssHour + ":" + ssMin);
                    log("醒来次数：" + walkingTimes);

                    long time = DateFormUtils.oneDayStart(currTime);
                    //step
                    StepData stepData = stepMap.get(time);
                    if (stepData == null
                            || stepData.getValue() < step) {
                        stepData = new StepData();
                        stepData.setTime(time);
                        stepData.setDetailTime(currTime);
                        stepData.setValue(step);
                        stepData.setKcal(kcal);
                        stepData.setUserId(currUserId);

                        stepMap.put(time, stepData);
                    } else {
                        stepData.setDetailTime(currTime);
                    }

                    //sleep
                    SleepData sleepData = sleepMap.get(time);
                    if (sleepData == null
                            || ssMin != 0 || ssHour != 0
                            || qsHour != 0 || qsMin != 0
                            || walkingTimes != 0) {
                        sleepData = new SleepData();
                        sleepData.setTime(time);
                        sleepData.setDeepValue(ssMin + ssHour * 60);
                        sleepData.setShallowValue(qsMin + qsHour * 60);
                        sleepData.setWalkingTimes(walkingTimes);
                        sleepData.setDetailTime(currTime);
                        sleepData.setUserId(currUserId);

                        sleepMap.put(time, sleepData);
                    }else {
                        sleepData.setDetailTime(currTime);
                    }
                } else if (data.get(1) == 0x11) {
                    //心率
                    //51 11 12 06 17 00 18 7A 7A
                    //12 06 17 00 18 7A 7A
                    //年 月 日 时 分 心率
                    int year = data.get(2);
                    int month = data.get(3);
                    int day = data.get(4);
                    int hour = data.get(5);
                    int min = data.get(6);
                    int heart = data.get(7);

                    log(year + "年" + month + "月" + day + "日  " + hour + "时" + min + "分");
                    log("心率：" + heart);

                    if (heart != 0) {
                        long time = DateFormUtils.parse2Long(year, month, day, hour, min);
//                        DateFormUtils.DateValue dateValue = DateFormUtils.parse(year, month, day, hour, min);

                        HeartData heartData = new HeartData();
                        heartData.setTime(time);
                        heartData.setValue(heart);
                        heartData.setUserId(currUserId);
                        heartDataList.add(heartData);
                    }
                } else if (data.get(1) == 0x12) {
                    //血氧
                    //51 12 12 06 17 13 08 63 63
                    //12 06 17 13 08：年月日时分
                    //63 63 ：血氧
                    int year = data.get(2);
                    int month = data.get(3);
                    int day = data.get(4);
                    int hour = data.get(5);
                    int min = data.get(6);
                    int oxygen = data.get(7);

                    log(year + "年" + month + "月" + day + "日  " + hour + "时" + min + "分");
                    log("血氧：" + oxygen);

                    if (oxygen != 0) {
                        long time = DateFormUtils.parse2Long(year, month, day, hour, min);
//                        DateFormUtils.DateValue dateValue = DateFormUtils.parse(year, month, day, hour, min);

                        OxygenData oxygenData = new OxygenData();
                        oxygenData.setTime(time);
                        oxygenData.setValue(oxygen);
                        oxygenData.setUserId(currUserId);
                        oxygenDataList.add(oxygenData);

                    }

                } else if (data.get(1) == 0x14) {
                    //血压
                    //51 14 12 06 17 10 2A 94 58
                    //12 06 17 10 2A：年月日时分
                    //94 58 ：收缩压、舒张压
                    int year = data.get(2);
                    int month = data.get(3);
                    int day = data.get(4);
                    int hour = data.get(5);
                    int min = data.get(6);
                    int bloodHigh = data.get(7);
                    int bloodLow = data.get(8);

                    log(year + "年" + month + "月" + day + "日  " + hour + "时" + min + "分");
                    log("血压：" + bloodHigh + "  " + bloodLow);

                    if (bloodHigh != 0 || bloodLow != 0) {
                        long time = DateFormUtils.parse2Long(year, month, day, hour, min);
//                        DateFormUtils.DateValue dateValue = DateFormUtils.parse(year, month, day, hour, min);

                        BloodData bloodData = new BloodData();
                        bloodData.setTime(time);
                        bloodData.setHighValue(bloodHigh);
                        bloodData.setLowValue(bloodLow);
                        bloodData.setUserId(currUserId);
                        bloodDataList.add(bloodData);
                    }
                }
            }
        }
        stepDataList.addAll(stepMap.values());
        sleepDataList.addAll(sleepMap.values());

        DataRepository.getInstance()
                .saveDropDownData(stepDataList, sleepDataList, heartDataList, oxygenDataList, bloodDataList, fatigueDataList)
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        BluetoothLeServiceV2.isDropDownRefresh = false;
                        BusHelper.post(new DropDownEvent(false));
                        UploadJobService.startUpload(context);

                        BusHelper.post(new LoadDataEndEvent());
                    }
                })
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////


    private void dealOneKeyMeasure(DataPacket dataPacket) {
        ArrayList<Byte> datas = dataPacket.data;
        //byte ---> int
        ArrayList<Integer> data = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            int ii = datas.get(i) & 0xff;
            data.add(ii);
        }

        //一键测量
        if (data.get(0) == 0x32) {
            //32 80 52 63 7E 55
            //52 63 7E 55 ：心率、血氧、高血压 、低血压
            int heart = data.get(2);
            int oxygen = data.get(3);
            int bloodHigh = data.get(4);
            int bloodLow = data.get(5);
            log("心率：" + heart);
            log("血氧：" + oxygen);
            log("血压：" + bloodHigh + "  " + bloodLow);

            OneKeyMeasureData oneKeyMeasureData = new OneKeyMeasureData(heart, oxygen, bloodHigh, bloodLow);
            BusHelper.post(oneKeyMeasureData);


        }
    }

    private void dealMeasure(DataPacket dataPacket) {
        if (status == Status.idle) {
            return;
        }
        ArrayList<Byte> datas = dataPacket.data;
        //byte ---> int
        ArrayList<Integer> data = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            int ii = datas.get(i) & 0xff;
            data.add(ii);
        }
        //单次、实时测量数据
        if (data.get(0) == 0x31) {
            //单次测量
            if (data.get(1) == 0x09 || data.get(1) == 0x11 || data.get(1) == 0x21) {
                if (data.get(1) == 0x09) {
                    //心率
                    int heart = data.get(2);
                    log("心率：" + heart);
                } else if (data.get(1) == 0x11) {
                    //血氧
                    int oxygen = data.get(2);
                    log("血氧：" + oxygen);
                } else if (data.get(1) == 0x21) {
                    //血压
                    int bloodHigh = data.get(2);
                    int bloodLow = data.get(3);
                    log("血压：" + bloodHigh + "  " + bloodLow);
                }

            } else {
                //实时测量
                if (data.get(1) == 0x0A) {
                    //心率
                    int heart = data.get(2);
                    log("心率：" + heart);

                    HeartData heartData = new HeartData();
                    heartData.setValue(heart);
                    BusHelper.post(heartData);
                } else if (data.get(1) == 0x12) {
                    //血氧
                    int oxygen = data.get(2);
                    log("血氧：" + oxygen);

                    OxygenData oxygenData = new OxygenData();
                    oxygenData.setValue(oxygen);
                    BusHelper.post(oxygenData);
                } else if (data.get(1) == 0x22) {
                    //血压
                    int bloodHigh = data.get(2);
                    int bloodLow = data.get(3);
                    log("血压：" + bloodHigh + "  " + bloodLow);

                    BloodData bloodData = new BloodData();
                    bloodData.setHighValue(bloodHigh);
                    bloodData.setLowValue(bloodLow);
                    BusHelper.post(bloodData);
                }
            }
        }
    }

    private void dealSleep(DataPacket dataPacket) {
        ArrayList<Byte> datas = dataPacket.data;
        //byte ---> int
        ArrayList<Integer> data = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            int ii = datas.get(i) & 0xff;
            data.add(ii);
        }
        //睡眠
        if (data.get(0) == 0x52 && data.get(1) == 0x80) {
            //52 80 12 06 18 06 27 02 00 30
            //12 06 18 06 27：年月日时分
            //02 ：ID=1:进入睡眠时间、ID=2：进入深睡时间
            //00 30  ：持续时间
            int year = data.get(2);
            int month = data.get(3);
            int day = data.get(4);
            int hour = data.get(5);
            int min = data.get(6);
            int id = data.get(7);
            int time = byteArrayToInt(new byte[]{0, 0, datas.get(8), datas.get(9)});

            log(year + "年" + month + "月" + day + "日  " + hour + "时" + min + "分");
            log("类型：" + (id == 1 ? "浅睡" : "!!深睡!!"));
            log("持续时间：" + time);
        }
    }


    private void startTimeChecker() {
        if (timeChecker != null && !timeChecker.isDisposed()) {
            timeChecker.dispose();
        }
        log("指令计时：" + cmd + "  开始");
        lastReceiveDataTime = System.currentTimeMillis();
        timeChecker = Observable.interval(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        //2秒没有接收到新数据
                        if (System.currentTimeMillis() - lastReceiveDataTime > 2000) {
                            log("指令计时：" + cmd + "  结束");
                            stopTransport();
                        }
                    }
                });
    }

    private void stopTimeChecker() {
        if (timeChecker != null && !timeChecker.isDisposed()) {
            timeChecker.dispose();
        }
    }


    public int byteArrayToInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    public static String byteArrayToString(ArrayList<Byte> buffer) {
        if (buffer == null) {
            return "";
        }
        final StringBuilder stringBuilder = new StringBuilder(buffer.size());
        if (buffer != null && buffer.size() > 0) {
            for (byte byteChar : buffer) {
                stringBuilder.append(String.format("%02X ", byteChar));
            }
        }
        return stringBuilder.toString();
    }


    private void log(String str) {
        System.out.println("            " + str);
    }
}
